#pragma once

#include <iostream>
#include <functional>
#include <string>
#include <cerrno>
#include <unordered_map>
#include <vector>
#include <cassert>
#include "Sock.hpp"
#include "Epoll.hpp"
#include "Log.hpp"
#include "Protocol.hpp"

class TcpServer;
class Connection;
using func_t = std::function<void(Connection *)>;
using callback_t = std::function<void(Connection *, std::string &request)>;
// sock必须要有自己独立的接受缓冲区和发送缓冲区
class Connection
{

public:
    Connection(int sock = -1)
        : _sock(sock), _tsvr(nullptr)
    {
    }

    void SetCallBack(func_t recv_cb, func_t send_cb, func_t execpt_cb)
    {
        _recv_cb = recv_cb;
        _send_cb = send_cb;
        _except_cb = execpt_cb;
    }

    ~Connection()
    {
    }

public:
    int _sock; // 负责进行io文件描述符
    // 三个回调是表征堆——sock进行特定的读写方法
    func_t _recv_cb;
    func_t _send_cb;
    func_t _except_cb;
    // 接受缓冲区 发送缓冲区
    std::string _inbuffer; // 不能处理二进制流，但文本可以
    std::string _outbuffer;
    // 设置堆tcpServer的回值指针
    TcpServer *_tsvr;

    // 扩展
    // 时间戳, 连接后长时间未使用断开连接
    uint64_t _lasttimestamp;

};

class TcpServer
{
    const static int gport = 8080;
    const static int gnum = 128;

public:
    TcpServer(int port = gport)
        : _port(port), _revs_num(gnum)
    {
        _listensock = Sock::Socket();
        Sock::Bind(_listensock, _port);
        Sock::Listen(_listensock);

        // 创建多路转接对象
        _poll.CreateEpoll();

        // 添加listensock到服务中
        AddConnection(_listensock, std::bind(&TcpServer::Accepter, this, std::placeholders::_1), nullptr, nullptr);

        // 构建一个获取就绪事件的缓冲区
        _revs = new struct epoll_event[_revs_num];
    }

    //  专门正对任意sock进行添加tcpserver
    void AddConnection(int sock, func_t recv_cb, func_t send_cb, func_t execpt_cb)
    {
        Sock::SetNonBlock(sock);

        // 添加sock到epoll模型中
        // 构建connetc对象，封装sock
        Connection *conn = new Connection(sock);
        conn->SetCallBack(recv_cb, send_cb, execpt_cb);
        conn->_tsvr = this;
        // conn->_lasttimestamp = time();
        // 将sock添加到epoll中
        // 任何多路转接的服务器，一般只默认打开堆读事件的关心，其他写事件只按需打开
        _poll.AddSockToEpoll(sock, EPOLLIN | EPOLLET);
        // 将对应的connection*对象指针添加到connection映射表中
        _connections.insert(std::make_pair(sock, conn));
    }

    void Accepter(Connection *conn)
    {
        // logMessage(DEBUG, "ACcepter been called");
        // listensock就绪不回阻塞
        while (true)
        {
            std::string clientip;
            uint16_t clientport;
            int accept_errno = 0;
            int sock = Sock::Accept(conn->_sock, &clientip, &clientport, &accept_errno);
            if (sock < 0)
            {
                if (accept_errno == EAGAIN || accept_errno == EWOULDBLOCK)
                    break; // 没有连接了
                else if (accept_errno == EINTR)
                    continue;
                else
                {
                    logMessage(WARNING, "accept error :%d : %s ", accept_errno, strerror(accept_errno));
                    break;
                }
            }
            // 将sock托管给Tcpserver
            if (sock > 0)
            {
                AddConnection(sock, std::bind(&TcpServer::Recver, this, std::placeholders::_1),
                              std::bind(&TcpServer::Sender, this, std::placeholders::_1),
                              std::bind(&TcpServer::Excepter, this, std::placeholders::_1));
                logMessage(DEBUG, "accept client %s:%d success,add to epoll&&serrver success,sock:%d",
                           clientip.c_str(), clientport, sock);
            }
        }
    }

    void EnableReadWrite(Connection *conn, bool readable, bool writeable)
    {
        uint32_t events = ((readable ? EPOLLIN : 0) | (writeable ? EPOLLOUT : 0));
        bool res = _poll.CtrlEpoll(conn->_sock, events);
        assert(res);
    }

    void Recver(Connection *conn)
    {
        // conn->_lasttimestamp = time(); //更新最近访问时间
        const int num = 1204;
        bool err = false;
        // logMessage(DEBUG, "Recver event exists, Recver() been called");
        // 面向字节流，进行常规读取
        while (true)
        {
            char buffer[num];
            ssize_t n = recv(conn->_sock, buffer, sizeof(buffer) - 1, 0);
            if (n < 0)
            {
                if (errno == EAGAIN || errno == EWOULDBLOCK)
                {
                    break;
                }
                else if (errno == EINTR)
                    continue;
                else
                {
                    logMessage(ERROR, "recv error, %d : %s", errno, strerror(errno));
                    conn->_except_cb(conn);
                    err = true;
                    break;
                }
            }
            else if (n == 0)
            {
                logMessage(ERROR, "client[%d] quit,server close[%d]", conn->_sock, conn->_sock);
                conn->_except_cb(conn);
                err = true;
                break;
            }
            else
            {
                // 读取成功
                buffer[n] = 0;
                conn->_inbuffer += buffer;
            }
        }
        logMessage(DEBUG, "conn->_inbuffer[sock:%d]: %s", conn->_sock, conn->_inbuffer.c_str());
        if (!err)
        {
            std::vector<std::string> messages;
            SplitMEssage(conn->_inbuffer, &messages);
            for (auto &msg : messages)
            {
                _cb(conn, msg);
            }
        }
    }

    void Sender(Connection *conn)
    {
        while (true)
        {
            ssize_t n = send(conn->_sock, conn->_outbuffer.c_str(), conn->_outbuffer.size(), 0);
            if (n > 0)
            {
                conn->_outbuffer.erase(0, n);
                if (conn->_outbuffer.empty())
                    break;
            }
            else
            {
                if (errno == EAGAIN || errno == EWOULDBLOCK)
                    break;
                else if (errno == EINTR)
                    continue;
                else
                {
                    // 错误
                    logMessage(ERROR, "send error, %d : %s", errno, strerror(errno));
                    conn->_except_cb(conn);
                    break;
                }
            }
        }
        if (conn->_outbuffer.empty())
            EnableReadWrite(conn, true, false); // 数据发完了关闭写
        else
            EnableReadWrite(conn, true, true);
    }

    void Excepter(Connection *conn)
    {
        // 不存在
        if(!IsConnectionExsits(conn->_sock)) return ;
        // 存在就从epoll中移出
        bool res = _poll.DelFromEpoll(conn->_sock);
        assert(res);
        // 从unorder_map中移出对应的对象
        _connections.erase(conn->_sock);
        // 关闭对象
        close(conn->_sock);
        // 释放对象
        delete conn;

        logMessage(DEBUG, "excepter 回收完毕，所有异常情况");
    }

    void LoopOnce()
    {
        int n = _poll.WaitEpoll(_revs, _revs_num);
        for (int i = 0; i < n; i++)
        {
            int sock = _revs[i].data.fd;
            uint32_t revents = _revs[i].events;

            // 如果出现异常，设置读写事件依然就绪
            // 将所有的异常全部交给red和wrie处理
            if(revents & EPOLLERR) revents |= (EPOLLIN | EPOLLOUT);
            if(revents & EPOLLHUP) revents |= (EPOLLIN | EPOLLOUT);


            if (revents & EPOLLIN)
            {
                if (IsConnectionExsits(sock) && _connections[sock]->_recv_cb != nullptr)
                {
                    _connections[sock]->_recv_cb(_connections[sock]);
                }
            }
            if (revents & EPOLLOUT)
            {
                if (IsConnectionExsits(sock) && _connections[sock]->_send_cb != nullptr)
                    _connections[sock]->_send_cb(_connections[sock]);
            }
        }
    }

    bool IsConnectionExsits(int sock)
    {
        auto iter = _connections.find(sock);
        if (iter == _connections.end())
            return false;
        else
            return true;
    }

    // void COnnectAliveCheck()
    // {
    //     // 遍历所有的_connections,英国检查最近的conn活动时间，
    //     // 若长时间没有活动就关闭该链接
    //     for(auto &iter : _connections)
    //     {
    //         uint64_t curtime = time();
    //         deadtime = curtime- iter->_lasttimestamp;
    //         if(deadtime > 某个超时值)
    //         {
    //             //进行相应的处理
    //         }
    //     }
    // }

    // 根据就绪的事件，进行特定的事件派发
    void Dispather(callback_t cb)
    {
        _cb = cb;
        while (true)
        {
            // COnnectAliveCheck();
            LoopOnce();
        }
    }

    ~TcpServer()
    {
        if (_listensock >= 0)
            close(_listensock);
        if (_revs)
            delete[] _revs;
    }

private:
    int _listensock;
    int _port;
    Epoll _poll;
    // sock映射到自己的connection
    std::unordered_map<int, Connection *> _connections;
    struct epoll_event *_revs;
    int _revs_num;

    // 上层的业务处理
    callback_t _cb;
};
